package controllers.systemadmin

import javax.inject.Inject

import controllers.BaseController
import models.JsonFormatters._
import models.{Login, User, UserQuery}
import repos.UserRepository

import scala.concurrent.ExecutionContext.Implicits.global

class UserController @Inject()(userRepository: UserRepository) extends BaseController {

  import userRepository.dbConfig.driver.api._

  def list = authJsonAction[UserQuery](Array("admin")) {
    (userQuery, request) => {
      val users = userRepository filter(
        user => {
          userQuery.userId.map(user.id === _).getOrElse(LiteralColumn(true)) &&
            userQuery.email.map(user.email === _).getOrElse(LiteralColumn(true)) &&
            userQuery.mobilePhoneNo.map(user.mobilePhoneNo === _).getOrElse(LiteralColumn(Option(true)))
        }, userQuery.page.getOrElse(1), userQuery.pageSize)
      users.map(us =>
        Map("success" -> true,
          "message" -> "列表查询成功",
          "total" -> us._1,
          "page" -> 1,
          "data" -> us._2)
      )
    }
  }

  def add = authJsonAction[User](Array("admin")) {
    (user, request) => {
      userRepository.save(user) map (u => Map("success" -> true,
        "message" -> "添加成功",
        "data" -> user.id))
    }
  }


  def modify = authJsonAction[User](Array("admin")) {
    (user, request) => {
      userRepository.update(user).map(u => Map("success" -> true,
        "message" -> "更新成功"))
    }
  }

  def remove = authJsonAction[Int](Array("admin")) {
    (id, request) => {
      userRepository.remove(id) map (result =>
        Map("success" -> true,
          "messsage" -> "删除成功")
        )
    }
  }

  def find = authJsonAction[Int](Array("admin")) {
    (id, request) => {
      userRepository.getById(id).map(ou => ou match {
        case Some(u) =>
          Map("success" -> true,
            "message" -> "获取信息成功",
            "data" -> u)

      })
    }
  }

  def login = jsonAction[Login] {
    (param, request) => {
      userRepository.login(param.userName, param.password)
        .map(profile => {
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "login complete",
            "data" -> profile)
        })
    }
  }

  def loginToken = jsonAction[Login] {
    (param, request) => {
      userRepository.loginToken(param.userName, param.password)
        .map { stoken =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "login complete",
            "data" -> stoken.token
          )
        }
    }
  }
}
